// Tools
// ------------------------
// $.getUrlVars();
// array.remove(MyArray);
// varInfo(MyVar);

//
// IE Display FIX function
// ------------------------
// $.fixInputText();
// $.ieSelectWidthFix();
// $.fixDisabledEvent();
// $('pre').fixOverflow();
// maxWidthHeightFix
// textareaFix
// randomNum(_start,_end);
/******************
JQuery extends Libs.

Read a page's GET URL variables and return them as an associative array.
e.g : [http://www.example.com/?me=myValue&name2=SomeOtherValue]
Calling getUrlVars() function would return you the following array:
{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}
ref:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar('name2');

//************** */
$.extend({
	debug_line_count : 0,
	debug: function(_str){
		var _de=$("#cf_debug");
		var _bug=_de.find("#cf_debug_logger");
		if( _de.length==0){
			// create
			this.debug_line_count=0;
			$("body").append("<div id='cf_debug' style='position:fixed;>position:absolute;left:0px;top:0px;z-index:9000;width:300px;height:400px;padding:10px;overflow:auto;background-color:black;color:#104852;'>"+
					"<span id='cf_debug_close' style='font-size:20px;background-color:cyan;color:black;padding:5px;margin:5px;float:right;'>X</span>"+
					"<span id='cf_debug_fullscreen' style='font-size:20px;background-color:cyan;color:black;padding:5px;margin:5px;float:right;'>Full</span>"+
					"<span id='cf_debug_clear' style='font-size:20px;background-color:cyan;color:black;padding:5px;margin:5px;float:right;'>Clear</span>"+
					"<h3>Debug:</h3><code id='cf_debug_logger' style='color:cyan;'></code></div>");
			_de=$("#cf_debug");
			_de.fadeTo(0, 0.8);
			_bug=_de.find("#cf_debug_logger");
			_de.find("#cf_debug_fullscreen").click(function(){
				if(!_de.hasClass("full")){
					_de.width("100%").height("100%").addClass("full");
					$(this).html("Small");
				} else {
					_de.width(300).height(400).removeClass("full");
					$(this).html("Full");
				}//if
			});
			_de.find("#cf_debug_clear").click(function(){
				this.debug_line_count=0;
				_bug.text("");
			});
			_de.find("#cf_debug_close").click(function(){
				_de.hide();
			});
			_de.dblclick(function(){
				$(this).hide();
			});
			_bug.html(this.debug_line_count+". "+_str);
		}else{
			if(typeof(_str)=="string"){
				this.debug_line_count++;
				_bug.prepend(this.debug_line_count+". "+_str+"\n<br/>");
			}else{
				this.debug_line_count=0;
				_bug.text("");//clear
			}
		}//if
		_de.show();	// display
	},
	getUrlVars: function() {
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split(/[&?]{1}[\w\d]+=/); // .split('&');
		for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	},
	// Fix IE input[type='text'] when it's parent have any display setting
	// e.g. position, top, left... will cause key_arrow_left/right, can't
	// move to the begin/end of textbox
	fixInputText : function(){
		if($.browser.msie){
			$("input[type='text']").each(function(){
				$(this).keyup(function(){
					$(this).css("margin","1").css("margin","0");
				});
			});
		}//if
	},
	ieSelectWidthFix : function(){
		// alert("ieSelectWidthFix");
		if($.browser.msie && $.browser.version<=8){
			$("select").each(function(){
				
				$(this).attr("origWidth", $(this).css("width"));
				$(this).mousedown(function(){
					$(this).css("width", "auto");
				});
				$(this).change(function(){
					$(this).css("width", $(this).attr("origWidth"));
				});
				$(this).blur(function(){
					$(this).css("width", $(this).attr("origWidth"));
				});
				$(this).change(function(){
					$(this).css("width", $(this).attr("origWidth"));
				});
				$(this).parent().append("<table class='fakebtn'><tr><td align='center' valign='center'><img src='./images/dropdown_expand.gif' /></td></tr></table>");
			});
			// $(".select_container").append("<table class='fakebtn'><tr><td align='center' valign='center'><img src='./images/dropdown_expand.gif' /></td></tr></table>");
			$(".fakebtn").click(function(){
				$(this).parent().parent().find("select").focus();
				// alert("hihi : "+ $(this).parent().parent().html() );
			});
		}//if
	},
	//Attaching mouse events to a disabled input element
	// please loaded on DOM ready
	fixDisabledEvent : function(){
		// find the disabled elements
		var $disabled = $("input:disabled,select:disabled");
		// loop through each of the disable elements and create an overlay
		$disabled.each(function (){
			// get the disabled element
			var $self = $(this)
			// get it's parent label element
			, $parent = $self.parent() // $self.closest("label")
			// create an overlay
			, $overlay = $("<div />");
			
			// style the overlay
			$overlay.css({
				// position the overlay in the same real estate as the original parent element
				position: "absolute"
				, top: $parent.position().top
				, left: $parent.position().left
				, width: $parent.outerWidth()
				, height: $parent.outerHeight()
				, zIndex: 10000
				// IE needs a color in order for the layer to respond to mouse events
				, backgroundColor: "#fff"
				// set the opacity to 0, so the element is transparent
				, opacity: 0
			})
			// attach the click behavior
			.click(function (){
				// trigger the original event handler
				if($self.attr("disabled")=="disabled"){
					alert("CLICK : "+ $self.attr('id'));
					return $self.trigger("click");
				}else
					return $self;
			})
			.mousedown(function (){
				if($self.attr("disabled")=="disabled")
					return $self.trigger("mousedown");
				else
					return $self;
			})
			.mouseup(function (){
				return $self.trigger("mouseup");
			});
			try{
				$overlay.contextMenu(function (){
					return $self.trigger("contextMenu");
				});
			}catch(e){}
			// add the overlay to the page
			$parent.append($overlay);
			// alert("fixDisabledEvent trigger");
		});
	},
	//
	// Get current version of Flash player
	//
	getFlashVersion : function(){
		// ie
		try {
			try {
				// avoid fp6 minor version lookup issues
				// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
				var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
				try { axo.AllowScriptAccess = 'always'; }
				catch(e) { return '6,0,0'; }
			} catch(e) {}
			return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
			// other browsers
		} catch(e) {
			try {
				if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
					return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
				}
			} catch(e) {}
		}
		return false;
	}
});
// Fix IE overflow scroll, unknown height scroll come out. 
// http://edskes.net/ie/ie8overflowandexpandingboxbugs.htm
// http://remysharp.com/2008/01/21/fixing-ie-overflow-problem/
//usage
//$('pre').fixOverflow().doOtherPlugin();
(function ($) {
	$.fn.fixOverflow = function () {
		if ($.browser.msie) {
			return this.each(function () {
				if (this.scrollWidth > this.offsetWidth) {
					$(this).css({ 'padding-bottom' : '20px', 'overflow-y' : 'hidden' });
				}
			});
		} else {
			return this;
		}
	};
	$.fn.autoscale = function(_parameter){
		/* ********************
			usage :
			- parameter:
				type : ["parent","nearest","bigger","smaller"]	// default = "parent"
				width : #num#
				height : #num#
				resize : true/false // default = false , will auto resize
			By Canis
		//****************** */
		this.each(function(){
			var _param={type:"parent",resize:true}
			if(_parameter!=undefined) _param = _parameter;
			var width = $(this).width();
			var height = $(this).height();
			var new_width;
			var new_height;
			var target_width;
			var target_height;
			var ratio = 1;
			var scaleBy = "";
			var mode = _param.type || "parent";
			if(!width) width = $(this).attr('width');
			if(!height) height = $(this).attr('height');
			
			switch( mode ){
				case "parent":
					$(this).hide();	// may effect on the parent's size
					target_width = $(this).parent().width();
					target_height= $(this).parent().height();
					$(this).show();
				break;
				default:
					target_width = _param.width || $(this).parent().width();
					target_height= _param.height|| $(this).parent().height();
				break;
			}//case
			
			if( (width / target_width) > (height / target_height) ){	// which side bigger
				if (width < target_width || width > target_width) {
					// scale by width
					scaleBy = "width";
					ratio = (height / width);
					new_width = target_width;
					new_height = (new_width * ratio);
					$(this).height(new_height).width(new_width);
				}//if
			}else{
				if (height < target_height || height > target_height) {
					// scale by height
					scaleBy = "height";
					ratio = (width / height);
					new_height = target_height;
					new_width = (new_height * ratio);
					$(this).height(new_height).width(new_width);
				}//if
			}//if
			/***
			alert("Parent width : "+ target_width +"px\nParent height : "+ target_height +"px\n"+
				"Self width : "+ width +"px\nSelf height : "+ height +"px\n"+
				"Scaling : "+ ratio +"\n"+
				"Scale By : "+ scaleBy +"\n"+
				"setup to : \nW = "+ new_width +"px\nH = "+ new_height+"px");
			//**/
		});
	};
	//
	//	exists
	//
	$.fn.exists = function(){
		return ($(this).length>0);
	};
	//
	//	visible
	//
	$.fn.visible = function(){
		$(this).css({visibility:"visible"});
	};
	$.fn.hidden = function(){
		$(this).css({visibility:"hidden"});
	};
	/*************
	unselectable
	*************/
	$.fn.disableSelection = function() {
		return this.each(function() {           
			$(this).attr('unselectable', 'on')
				.css({
					'-moz-user-select':'none',
					'-webkit-user-select':'none',
					'user-select':'none'
				})
				.each(function() {
					this.onselectstart = function() { return false; };
				});
		});
	};
})(jQuery);
////////////////////////////////////////////////////////////////////////////////////////////
//Normal function
//
//
// var MyArray= new Array("a","b","c");
// array.remove(MyArray);
//
function RemoveArray(array,attachId){
	for(var i=0,n=0;i<array.length;i++){
		if(array[i]!=attachId){
			array[n++]=array[i];
		}
	}
	array.length -= 1;
}
//
// varInfo
// loop the input variable, and return all info by string.[pre] format
function varInfo(_var){
	var _str="[Variable info :]--------------\n";
	switch( typeof(_var)){
		case "string": case "number": case "boolean":
			_str+="type : "+ typeof(_var)+"\n";
			_str+="value : "+ _var+"\n";
		break;
		case "object":
			if( _var.length>=0 ){
				_str+="type : array\n";
			}else{
				_str+="type : object\n";
			}
			_str+= childInfo(_var)+"\n";
		break;
		default:
			_str+="unknow type\n";
		break;
	}//case
	_str+="--------------------[End Info]\n";
	return _str;
}
function childInfo(_var){
	var items = [];
	var _str="";
	$.each(_var, function(key, val) {
		if( typeof(val)=="object" ){
			items.push("."+key+"="+childInfo(val)+"\n");
		}else{
			items.push("."+key+"="+val+"\n");
		}//if
	});
	_str= items.join("\n");
	return _str;
}
/*
* Recursively merge properties of two objects 
*  http://code.google.com/p/jquery-json/ [!]** REQUEST **[!]
*/
function MergeRecursive(obj1, obj2) {
	for (var p in obj2) {
		try {
			// Property in destination object set; update its value.
			if ( obj2[p].constructor==Object ) { // typeof(obj2[p])=="object"
				// throw error when obj1[xxxx]==undefined
				obj1[p] = MergeRecursive(obj1[p], obj2[p]);
			} else {
				obj1[p] = obj2[p];
			}//if
		} catch(e) {
			// Property in destination object not set; create it and set its value.
			obj1[p] = obj2[p];
		}
	}
	return obj1;
}
/*
 * Dame it IE6 before, and now is IE8
 * why you bam selectionStart / selectionEnd,
 * selection.createRange ? WTF ?
 * Bill gate YMF
 */
function getInputSelection(el) {
	var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange;
	if(typeof el.selectionStart == "number" && typeof el.selectionEnd == "number"){
		start = el.selectionStart;
		end = el.selectionEnd;
	} else {
		range = document.selection.createRange();
		if (range && range.parentElement() == el) {
			len = el.value.length;
			normalizedValue = el.value.replace(/\r\n/g, "\n");
			// Create a working TextRange that lives only in the input
			textInputRange = el.createTextRange();
			textInputRange.moveToBookmark(range.getBookmark());
			// Check if the start and end of the selection are at the very end
			// of the input, since moveStart/moveEnd doesn't return what we want
			// in those cases
			endRange = el.createTextRange();
			endRange.collapse(false);
			if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
				start = end = len;
			} else {
				start = -textInputRange.moveStart("character", -len);
				start += normalizedValue.slice(0, start).split("\n").length - 1;
				if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
					end = len;
				} else {
					end = -textInputRange.moveEnd("character", -len);
					end += normalizedValue.slice(0, end).split("\n").length - 1;
				}
			}
		}
	}
	return {
		start: start,
		end: end
	};
}
/*************
All Browser Fix
Firefox, Chrome, IE, IE6
*************/
function browserPatch(){
	textareaFix();
	setTimeout("maxWidthHeightFix()", 10 );
}
/*************
 textarea Fix for publication_summary.jsp
 IE stupid texarea row height fix.
*************/
function textareaFix(){
	var _rows, _fontSize, _lineHeight;
	if($.browser.msie){
		$("textarea.textarea_fix").each(function(){
			_rows = parseInt( $(this).attr("rows") );
			_fontSize = parseInt( $(this).css('font-size').replace('px','') );
			_lineHeight = parseInt( $(this).css('line-height') ) || Math.floor(_fontSize)*1.5;
			$(this).height( _lineHeight*_rows );
		});
	}//if
	// $.debug("textareaFix : IE "+ $.browser.msie +" found:"+ $("textarea.textarea_fix").length);
}//fn
/*************
max-width-height fix for IE
*************/
function maxWidthHeightFix(_obj){
	if($.browser.msie){
		var _mwh = ".maxWidthHeightFix";	// the class to active max width/height checking.
		var _h,_w;
		if(_obj!=null) _mwh=_obj+" "+_mwh;	// target someone.
		$(_mwh).each(function(){
			_w = $(this).attr('maxw') || false;	// when max width setted
			_h = $(this).attr('maxh') || false;	// when max height setted
			// $.debug("MaxWH w:"+$(this).width()+">"+_w+", h:"+ $(this).get(0).scrollHeight+">"+_h);
			/*******************************
			 * 1st check, will enforce all hidden object to target width/height,
			 * 2nd check, will reset the width/height to auto and get the REAL value to access the fit size
			 *******************************/
			if(_h){
				$(this).css("height","auto");
				if($(this).height() < _h && $(this).height()>0){
					$(this).css("height","auto");
				}else{
					$(this).css("height", _h);
				}//if
			}//if
			if(_w!=0){
				$(this).css("width","auto");
				if($(this).width() < _w && $(this).width()>0){
					$(this).css("width","auto");
				}else{
					$(this).css("width", _w);
				}//if
			}//if
		});
	}//if
}//fn
/*************
Random Number : more balance
*************/
function randomNum(_start,_end){
	// include _end number.
	var _range = 10;
	var _rtn=0;
	if(_start==null) _start=10;
	if(_end==null){ _end=_start; _start=0; };
	while( Math.abs(_end-_start)>_range ){ _range*=10; }
	var _tmp = Math.random()*_range;
	_rtn = Math.ceil(_tmp/(_range/(_end-_start+1)))+_start-1;
	// $.debug("start:"+_start+", end:"+_end+" return:"+ _rtn+"("+_tmp+")");
	return _rtn;
}